<template lang="pug">
div
  BottomSheet(
      :isVisible="trayIsVisible"
      @close="trayIsVisible = false"
      )
    Tray(
        :trayList="trayList"
        :trayDropDownList="trayDropDownList"
        @check-input="checkInput"
        )

  BottomSheet(
      :isVisible="allInIsVisible"
      @close="allInIsVisible = false"
      )
    AllIn(
        :isVisible="allInIsVisible"
        :bodyList="bodyList"
        :ReceiveId="info && info.ReceiveId"
        :PullSupplierNum="info && info.PullSupplierNum"
        )

  FixedScroll
    div(slot="fixed")
      PageHeader(pageTitle="送验收货")
        div.save(
            v-if="$root.User.permMap['Save(送验收货)']"
            slot="right"
            :class="{'save-disabled': !saveEnabled, active: saveEnabled}"
            @click="save(false)"
            ) 保存

      ScanSearch(
          placeholder="送验单号"
          :initSearchValue="searchValue"
          @search="search"
          @scan="search"
          )
      
      g-v.info(v-if="info")
        KvPair(v-if="info.EWmNo" k="实体仓库" :v="info.EWmNo")
        KvPair(v-if="info.PullSupplierNum" k="厂家编号" :v="info.PullSupplierNum")
        KvPair(v-if="info.UpdateUser" k="收货人" :v="info.UpdateUser")
        KvPair(
            v-if="info.UpdateDate"
            k="收货时间"
            :v="info.UpdateDate | Date"
            :kStyle="kvStyle.k"
            :vStyle="kvStyle.v"
            )

    StatTable.table(
        slot="scroll"
        :headList="headList"
        :body="body"
        :isLoading="isLoading"
        :disabled="!saveEnabled"
        @check-input="checkInput"
        )

    g-h.bottom-bar(slot="fixed-bottom" j-c="space-between")
      Button(
          @click="trayIsVisible = true"
          text="添加托盘"
          :disabled="trayButton.disabled"
          )
      Button(
          v-if="$root.User.permMap['Save_Zheng(送验收货)']"
          @click="allInIsVisible = true"
          text="整入整出"
          :disabled="allInButton.disabled"
          )

</template>

<script>
import api from "$api"
import util from "$util"

import Tray from "./Tray.vue"
import AllIn from "./AllIn.vue"

export default {
  components: {
    Tray,
    AllIn,
  },
  data() {
    return {
      searchValue: "",
      isLoading: false,
      saveEnabled: false,
      hasIllegalInput: false,

      loading: {
        search: false,
        save: false,
      },

      trayIsVisible: false, // 是否显示托盘按钮
      trayList: [ // 托盘数据
        { code: "", num: 0, title: "" },
      ],
      trayDropDownList: [], // 托盘下拉列表
      trayButton: {
        disabled: true,
      },

      allInIsVisible: false, // 是否显示整入整出按钮
      allInButton: {
        disabled: true,
      },

      info: null,
      headList: [
        { field: "PartNo", title: "物料号", checked: true },
        { field: "PartName", title: "物料名称", checked: true },
        { field: "RequiredQty", title: "送验数", checked: true },
        { field: "ActualQty", title: "累计件数", checked: true },
        { field: "Num", title: "接收数", checked: true, isInput: true },
        { field: "WmNo", title: "逻辑仓库", checked: true },
        { field: "PackageModel", title: "器具编号", checked: true },
        { field: "RequiredBoxNum", title: "送验数", checked: true },
        { field: "ActualBoxNum", title: "累计箱数", checked: true },
        { field: "BoxNum", title: "接收数", checked: true, isInput: true },
        { field: "Dloc", title: "库位", checked: true },
      ],
      body: {
        list: [],
      },

      kvStyle: {
        k: {
          width: "30%",
        },
        v: {
          width: "70%",
        },
      },
    }
  },
  computed: {
    bodyList() {
      let lst = []
      let i = 0
      for (let item of this.body.list) {
        lst[i] = {
          ReceiveDetailId: item.ReceiveDetailId,
          ReceiveId: item.ReceiveId,
          Num: item.Num,
          BoxNum: item.BoxNum,
          CheckType: item.CheckType,
        }
        i++
      }
      return lst
    },
  },
  methods: {
    async search(value) {
      if (this.loading.search) {
        return
      }
      if (value === "") {
        return
      }

      this.loading.search = true
      try {
        let data = await api.OrderSearch({
          ReceiveNo: value,
        })
        this.reset()

        for (let item of data.ReceiveDetailInfo) {
          if (item.IsBatch === 0) {
            util.Alert(`物料[${item.PartNo}]的管理模式未维护,请维护库位与物料关系后操作`)
            return
          }
          if (item.IsBatch === 2) {
            util.Alert("该单据需在电池收货界面操作")
            return
          }
        }

        switch (data.ReceiveInfo.ConfirmFlag) {
          case 2:
            util.Toast("已完成")
            break
          case 9:
            this.saveEnabled = true
            this.trayButton.disabled = false
            break
          default:
            this.saveEnabled = true
            this.trayButton.disabled = false
            this.allInButton.disabled = false
            break
        }

        this.info = data.ReceiveInfo
        this.body.list = data.ReceiveDetailInfo

        // 给托盘下拉列表赋值
        let dropdownList = new Array(data.PackageApplianceInfo.length)
        let i = 0
        for (let item of data.PackageApplianceInfo) {
          dropdownList[i] = {
            name: `${item.PackageNo}(${item.PackageCname})`,
            id: item.PackageNo,
          }
          i++
        }
        this.trayDropDownList = dropdownList
        this.trayList = [
          { code: "", num: 0, title: "" },
        ]

      } catch(err) {
        this.$root.error(err)
      } finally {
        this.isLoading = false
        this.loading.search = false
      }
    },

    async save(IgnoreMaxLimit) {
      if (this.loading.save) {
        return
      }
      if (!(this.info && this.saveEnabled)) {
        return
      }
      if (this.hasIllegalInput) {
        util.Alert("输入框中包含不合法的数据")
        return
      }

      for (let item of this.body.list) {
        if (parseInt(item.Num) > item.RequiredQty - item.ActualQty) {
          util.Alert(`物料${item.PartNo}的接收数不能大于剩余需求数量`)
          return
        }
        if (parseInt(item.BoxNum) > item.RequiredBoxNum - item.ActualBoxNum) {
          util.Alert(`物料${item.PartNo}的器具接收数不能大于剩余器具需求数量`)
          return
        }
      }

      // 获取托盘数据
      let trayTable = {}
      for (let item of this.trayList) {
        let num = parseInt(item.num)
        if (item.code && num) {
          let oldNum = trayTable[item.code] || 0
          trayTable[item.code] = num + oldNum
        }
      }

      this.loading.save = true
      util.Indicator.open()
      try {
        await api.OrderSave({
          receiveDetailList: this.body.list,
          ReceiveId: this.info.ReceiveId,
          trayTable,
          IgnoreMaxLimit,
        })
        util.Indicator.close()
        util.Toast("保存成功")
        await this.search(this.info.ReceiveNo)
      } catch(err) {
        util.Indicator.close()
        this.$root.error(err, true)
        let special = "是否继续保存"
        if (typeof err.msg === "string" && err.msg.indexOf(special) > -1) {
          util.Confirm(err.msg).then((action) => {
            this.save(true)
          }).catch(() => {})
        } else {
          util.Alert(err.msg || "服务器错误")
        }
      } finally {
        this.isLoading = false
        this.loading.save = false
      }
    },

    // 重置本页的状态
    reset() {
      this.saveEnabled = false
      this.trayButton.disabled = true
      this.allInButton.disabled = true
    },

    // 检查输入数据
    checkInput(v, rowIndex, field) {
      let isNatural = /^(0|[1-9]\d*)$/.test(v)
      if (!isNatural) {
        this.hasIllegalInput = true
        util.Alert(`错误的输入: ${v}`)
        return
      }

      if (this.hasIllegalInput) {
        this.hasIllegalInput = false
      }
      if (rowIndex == undefined) {
        return
      }

      let row = this.body.list[rowIndex]
      if (row.Package <= 0) {
        row.Package = 1
      }
      let boxNum = Math.ceil(row.Num / row.Package)
      switch (field) {
        case "Num":
          if (boxNum > row.RequiredBoxNum - row.ActualBoxNum) {
            boxNum = row.RequiredBoxNum - row.ActualBoxNum
          }
          row.BoxNum = boxNum
          if (parseInt(row.Num) > row.RequiredQty - row.ActualQty) {
            util.Alert(`物料${row.PartNo}的接收数不能大于剩余需求数量`)
            this.hasIllegalInput = true
            return
          }
          break
        case "BoxNum":
          if (parseInt(v) > boxNum) {
            util.Alert(`器具接收数需小于本次件数除以收容数(${boxNum})`)
            this.hasIllegalInput = true
            return
          }
          if (parseInt(row.BoxNum) > row.RequiredBoxNum - row.ActualBoxNum) {
            util.Alert(`物料${row.PartNo}的器具接收数不能大于剩余需求数量`)
            this.hasIllegalInput = true
          }
          break
      }
    },

    registerScanner() {
      util.registerScanner((data) => {
        this.searchValue = data
        this.search(data)
      })
    },

  },

  created() {
    this.registerScanner()
  },
}
</script>

<style lang="stylus" scoped>

.save-disabled
  color: grey500

.active:active
  active-color()

.info
  border: 1px solid grey200

.table
  scan-table()

.bottom-bar
  bottom-bar()

</style>
